package chen.web.search;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import chen.web.forum.Subject;

public class SubjectIndex extends Config {


	private static Map<String, Float> boostMap = new HashMap<String, Float>();
	static{
		boostMap.put(SubjectDocument.Field_Title, 2f);
		boostMap.put(SubjectDocument.Field_Content, 1f);
	}
	
	public SubjectIndex(File indexDirectory, boolean create) {
		super(indexDirectory, create);
		// TODO Auto-generated constructor stub
	}
	
	public void write(Subject subject){
		SubjectDocument doc = new SubjectDocument();
		try {
			super.getIndexWriter().addDocument(doc.getDocument(subject));
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void close(){
		try {
			super.getIndexWriter().close();
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static String[] fileds = new String[]{SubjectDocument.Field_Title, SubjectDocument.Field_Content};
	public void search(String str){
		try {
			IndexSearcher searcher = new IndexSearcher(FSDirectory.open(super.getIndexDirectory()));
			MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LUCENE_30, fileds, super.getAnalyzer(), boostMap);
			Query query = parser.parse(str);
			TopDocs topDocs = searcher.search(query, 5);
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
